package com.smart.village.big.screen.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.smart.village.big.screen.mapper.ChangeACTMapper;
import com.smart.village.big.screen.service.ChangeACTService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ChangeACTServiceImpl implements ChangeACTService {
    @Autowired
    private ChangeACTMapper changeACTMapper;

    @Override
    public List<JSONObject> getAllBluePlateTags(String tagSerialNumber) {
        return changeACTMapper.getAllBluePlateTags(tagSerialNumber);
    }

    @Override
    public JSONObject getServiceResourcesCoordsList(String townNumber, String villageNumber, String tagSerialNumber) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("type", "FeatureCollection");
        JSONObject crs = new JSONObject();
        crs.put("type", "name");
        JSONObject crsP = new JSONObject();
        crsP.put("name", "EPSG:4490");
        crs.put("properties", crsP);

        jsonObject.put("crs", crs);
        List<JSONObject> list = changeACTMapper.getServiceResourcesCoordsList(townNumber, villageNumber, tagSerialNumber);
        List<JSONObject> features = Lists.newArrayList();
        for (JSONObject coords : list) {
            JSONObject feature = new JSONObject();
            feature.put("type", "Feature");
            feature.put("id", coords.getString("Shop_SerialNumber"));
            JSONObject geometry = new JSONObject();
            geometry.put("type", "point");
            geometry.put("coordinates", coords.getString("Coord").replace(" ", ""));
            feature.put("geometry", geometry);
            feature.put("properties", coords);
            if (!ObjectUtils.isEmpty(coords.getString("Coord")) && !coords.getString("Coord").replace(" ", "").equals("[]]")) {
                coords.remove("Coords");
                coords.remove("Coord");
                features.add(feature);
            }
        }
        jsonObject.put("features", features);
        return jsonObject;
    }

    @Override
    public JSONObject getImportentTourScence() {
        JSONObject jsonObject = new JSONObject();
        List<JSONObject> list = changeACTMapper.getImportentTourScence();
        jsonObject.put("list", list);
        jsonObject.put("total", list.size());
        return jsonObject;
    }

    @Override
    public JSONObject getTouristFeedback(String townNumber, String villageNumber, int pageNum, int pageSize) {
        //todo 定一下事件类型都有啥
        int Up_Cnt = changeACTMapper.getTouristFeedbackUpCnt(townNumber, villageNumber);
        int Deal_Cnt = changeACTMapper.getTouristFeedbackdDealCnt(townNumber, villageNumber);
        String SatisfactionRate = "0";
        JSONObject Satisfaction = changeACTMapper.getTouristFeedbackSatisfactionRate(townNumber, villageNumber);
        if (!ObjectUtils.isEmpty(Satisfaction)) {
            Integer satisfactionCnt = Satisfaction.getInteger("满意数量");
            Integer totalCnt = Satisfaction.getInteger("总数量");
            if (satisfactionCnt == 0) {
                SatisfactionRate = "0";
            } else {
                double v = satisfactionCnt.doubleValue() / totalCnt.doubleValue();
                DecimalFormat df = new DecimalFormat("#.00");
                String str = df.format(v * 100);
                SatisfactionRate = str;
            }
        }
        PageHelper.startPage(pageNum, pageSize);
        List<JSONObject> List_Data = changeACTMapper.getTouristFeedback(townNumber, villageNumber);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("Up_Cnt", Up_Cnt);
        jsonObject.put("Deal_Cnt", Deal_Cnt);
        double v = (double) Deal_Cnt / (double) Up_Cnt;
        DecimalFormat df = new DecimalFormat("#.00");
        String DealRate = df.format(v * 100);
        jsonObject.put("DealRate", DealRate);
        jsonObject.put("SatisfactionRate", SatisfactionRate);
        jsonObject.put("List_Data", List_Data);
        return jsonObject;
    }

    @Override
    public JSONObject getTravelAgency(String townNumber, String villageNumber, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<JSONObject> complaintEvent = changeACTMapper.getTravelAgency(townNumber, villageNumber);
        // 加入 rank
        for (int i = 0; i < complaintEvent.size(); i++) {
            JSONObject jsonObject1 = complaintEvent.get(i);
            jsonObject1.put("Rank", i + 1);
        }
        PageInfo<JSONObject> pageInfo = new PageInfo<>(complaintEvent);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list", pageInfo.getList());
        jsonObject.put("total", pageInfo.getTotal());
        return jsonObject;
    }

    @Override
    public JSONObject getHomestayIntroduction(String townNumber, String villageNumber, int pageNum, int pageSize) {
        JSONObject homestayIntroduction = changeACTMapper.getHomestayIntroduction1(townNumber, villageNumber);
        PageHelper.startPage(pageNum, pageSize);
        List<JSONObject> list = changeACTMapper.getHomestayIntroduction2(townNumber, villageNumber);
        for (int i = 0; i < list.size(); i++) {
            list.get(i).put("rank", i + 1);
        }
        PageInfo<JSONObject> pageInfo = new PageInfo<>(list);
        homestayIntroduction.put("list", pageInfo.getList());
        homestayIntroduction.put("total", pageInfo.getTotal());
        return homestayIntroduction;
    }

    @Override
    public JSONObject getServiceResourcesList(String townNumber, String villageNumber, String resourceType, int pageNum, int pageSize) {
        JSONObject jsonObject = new JSONObject();
        List<JSONObject> list;
        if ("公共厕所".equals(resourceType)) {
            String bluePlateTags1 = "'公共厕所'";
            list = changeACTMapper.getBluePlateTagsByTagName(townNumber, villageNumber, bluePlateTags1);
            jsonObject.put("list", list);
        } else if ("医院".equals(resourceType)) {
            String bluePlateTags1 = "'医院'";
            list = changeACTMapper.getBluePlateTagsByTagName(townNumber, villageNumber, bluePlateTags1);
            jsonObject.put("list", list);
        } else if ("药店".equals(resourceType)) {
            String bluePlateTags1 = "'药店'";
            list = changeACTMapper.getBluePlateTagsByTagName(townNumber, villageNumber, bluePlateTags1);
            jsonObject.put("list", list);
        } else if ("避险区".equals(resourceType)) {
            String bluePlateTags1 = "'紧急避难场所','短期避难场所','长期避难场所'";
            list = changeACTMapper.getBluePlateTagsByTagName(townNumber, villageNumber, bluePlateTags1);
            jsonObject.put("list", list);
        }

        String bluePlateTags1 = "'公共厕所'";
        List<JSONObject> complaintEvent1 = changeACTMapper.getBluePlateTagsByTagName(townNumber, villageNumber, bluePlateTags1);
        String bluePlateTags2 = "'医院'";
        List<JSONObject> complaintEvent2 = changeACTMapper.getBluePlateTagsByTagName(townNumber, villageNumber, bluePlateTags2);
        String bluePlateTags3 = "'药店'";
        List<JSONObject> complaintEvent3 = changeACTMapper.getBluePlateTagsByTagName(townNumber, villageNumber, bluePlateTags3);
        String bluePlateTags4 = "'紧急避难场所','短期避难场所','长期避难场所'";
        List<JSONObject> complaintEvent4 = changeACTMapper.getBluePlateTagsByTagName(townNumber, villageNumber, bluePlateTags4);

        jsonObject.put("toilet", complaintEvent1.size());
        jsonObject.put("hospital", complaintEvent2.size());
        jsonObject.put("drugStore", complaintEvent3.size());
        jsonObject.put("emergencyDiversion", complaintEvent4.size());

        return jsonObject;
    }

    @Override
    public JSONObject getTrafficFlow(String townNumber, String villageNumber) {
        JSONObject jsonObject = new JSONObject();
        int totalCar;
        int currentCustomer;
        int trafficJamCnt;
        int warningEvent;

        totalCar = changeACTMapper.getTotalCar(townNumber, villageNumber);
        currentCustomer = changeACTMapper.getCurrentCustomer(townNumber, villageNumber);
        trafficJamCnt = changeACTMapper.getTrafficJamCnt(townNumber, villageNumber);
        warningEvent = changeACTMapper.getWarningEvent(townNumber, villageNumber);

        jsonObject.put("totalCar", totalCar);
        jsonObject.put("currentCustomer", currentCustomer);
        jsonObject.put("trafficJamCnt", trafficJamCnt);
        jsonObject.put("warningEvent", warningEvent);
        return jsonObject;
    }

    @Override
    public JSONObject getTrafficFlowAnalysis(String townNumber, String villageNumber) {
        List<String> hourDataList = new ArrayList<>();
        hourDataList.add("08:00");
        hourDataList.add("09:00");
        hourDataList.add("10:00");
        hourDataList.add("11:00");
        hourDataList.add("12:00");
        hourDataList.add("13:00");
        hourDataList.add("14:00");
        hourDataList.add("15:00");
        hourDataList.add("16:00");
        hourDataList.add("17:00");
        hourDataList.add("18:00");

        List<JSONObject> trafficFlowAnalysisData = changeACTMapper.getTrafficFlowAnalysis(townNumber, villageNumber);
        java.util.Map<String, List<JSONObject>> hourDataMap = trafficFlowAnalysisData.stream().collect(Collectors.groupingBy(jsonObject -> jsonObject.getString("Hour_Data")));

        List<Integer> data = new ArrayList<>();
        // 根据产生的数据，通过时间进行分组，将景点名称、平均速度、拥堵情况进行归类组成不同的集合
        for (String s : hourDataList) {
            int carCnt = 0;
            for (Map.Entry<String, List<JSONObject>> entry : hourDataMap.entrySet()) {
                if (entry.getKey().equals(s)) {
                    carCnt = Integer.parseInt(entry.getValue().get(0).getString("Car_Cnt"));
                }
            }
            data.add(carCnt);
        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("series", data);
        jsonObject.put("xAxis", hourDataList);


        return jsonObject;
    }

    @Override
    public JSONObject getTrafficFlowRealTime(String townNumber, String villageNumber,int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<JSONObject> trafficFlowRealTime = changeACTMapper.getTrafficFlowRealTime(townNumber, villageNumber);
        PageInfo<JSONObject> pageInfo = new PageInfo<>(trafficFlowRealTime);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list", pageInfo.getList());
        jsonObject.put("total", pageInfo.getTotal());
        return jsonObject;
    }

    @Override
    public JSONObject getCustomerAnalysis(String townNumber, String villageNumber, String dateType) {
        List<String> hourDataList = new ArrayList<>();
        hourDataList.add("08:00");
        hourDataList.add("09:00");
        hourDataList.add("10:00");
        hourDataList.add("11:00");
        hourDataList.add("12:00");
        hourDataList.add("13:00");
        hourDataList.add("14:00");
        hourDataList.add("15:00");
        hourDataList.add("16:00");
        hourDataList.add("17:00");
        hourDataList.add("18:00");

        if (dateType.equals("今日")) {
            List<JSONObject> todayData = changeACTMapper.getCustomerAnalysis(townNumber, villageNumber, "today");
            java.util.Map<String, List<JSONObject>> todayHourDataMap = todayData.stream().collect(Collectors.groupingBy(jsonObject -> jsonObject.getString("Hour_Data")));

            List<Integer> data1 = new ArrayList<>();
            // 根据产生的数据，通过时间进行分组，将景点名称、平均速度、拥堵情况进行归类组成不同的集合
            for (String s : hourDataList) {
                int carCnt = 0;
                for (Map.Entry<String, List<JSONObject>> entry : todayHourDataMap.entrySet()) {
                    if (entry.getKey().equals(s)) {
                        carCnt = Integer.parseInt(entry.getValue().get(0).getString("Person_Cnt"));
                    }
                }
                data1.add(carCnt);
            }

            List<JSONObject> yesterdayData = changeACTMapper.getCustomerAnalysis(townNumber, villageNumber, "yesterday");
            java.util.Map<String, List<JSONObject>> yesterdayHourDataMap = yesterdayData.stream().collect(Collectors.groupingBy(jsonObject -> jsonObject.getString("Hour_Data")));

            List<Integer> data2 = new ArrayList<>();
            // 根据产生的数据，通过时间进行分组，将景点名称、平均速度、拥堵情况进行归类组成不同的集合
            for (String s : hourDataList) {
                int carCnt = 0;
                for (Map.Entry<String, List<JSONObject>> entry : yesterdayHourDataMap.entrySet()) {
                    if (entry.getKey().equals(s)) {
                        carCnt = Integer.parseInt(entry.getValue().get(0).getString("Person_Cnt"));
                    }
                }
                data2.add(carCnt);
            }



            List<JSONObject> legendData = new ArrayList<>();
            JSONObject legend1 = new JSONObject();
            legend1.put("name", "当前客流量");
            legend1.put("code", "data1");
            legendData.add(legend1);
            JSONObject legend2 = new JSONObject();
            legend2.put("name", "昨日客流量");
            legend2.put("code", "data2");
            legendData.add(legend2);



            JSONObject jsonObject = new JSONObject();

            jsonObject.put("xData", hourDataList);
            jsonObject.put("legend", legendData);
            jsonObject.put("data1", data1);
            jsonObject.put("data2", data2);

            return jsonObject;

        }
        if (dateType.equals("本周")) {
            List<JSONObject> currentWeekData = changeACTMapper.getCustomerAnalysis(townNumber, villageNumber, "currentWeek");
            java.util.Map<String, List<JSONObject>> currentWeekHourDataMap = currentWeekData.stream().collect(Collectors.groupingBy(jsonObject -> jsonObject.getString("Hour_Data")));

            List<Integer> data1 = new ArrayList<>();
            // 根据产生的数据，通过时间进行分组，将景点名称、平均速度、拥堵情况进行归类组成不同的集合
            for (String s : hourDataList) {
                int carCnt = 0;
                for (Map.Entry<String, List<JSONObject>> entry : currentWeekHourDataMap.entrySet()) {
                    if (entry.getKey().equals(s)) {
                        carCnt = Integer.parseInt(entry.getValue().get(0).getString("Person_Cnt"));
                    }
                }
                data1.add(carCnt);
            }

            List<JSONObject> lastWeekData = changeACTMapper.getCustomerAnalysis(townNumber, villageNumber, "lastWeek");
            java.util.Map<String, List<JSONObject>> lastWeekHourDataMap = lastWeekData.stream().collect(Collectors.groupingBy(jsonObject -> jsonObject.getString("Hour_Data")));

            List<Integer> data2 = new ArrayList<>();
            // 根据产生的数据，通过时间进行分组，将景点名称、平均速度、拥堵情况进行归类组成不同的集合
            for (String s : hourDataList) {
                int carCnt = 0;
                for (Map.Entry<String, List<JSONObject>> entry : lastWeekHourDataMap.entrySet()) {
                    if (entry.getKey().equals(s)) {
                        carCnt = Integer.parseInt(entry.getValue().get(0).getString("Person_Cnt"));
                    }
                }
                data2.add(carCnt);
            }

            List<JSONObject> legendData = new ArrayList<>();
            JSONObject legend1 = new JSONObject();
            legend1.put("name", "当前客流量");
            legend1.put("code", "data1");
            legendData.add(legend1);
            JSONObject legend2 = new JSONObject();
            legend2.put("name", "上周客流量");
            legend2.put("code", "data2");
            legendData.add(legend2);



            JSONObject jsonObject = new JSONObject();

            jsonObject.put("xData", hourDataList);
            jsonObject.put("legend", legendData);
            jsonObject.put("data1", data1);
            jsonObject.put("data2", data2);

            return jsonObject;
        }
        if (dateType.equals("本月")) {
            List<JSONObject> currentMonthData = changeACTMapper.getCustomerAnalysis(townNumber, villageNumber, "currentMonth");
            java.util.Map<String, List<JSONObject>> currentMonthDataHourDataMap = currentMonthData.stream().collect(Collectors.groupingBy(jsonObject -> jsonObject.getString("Hour_Data")));

            List<Integer> data1 = new ArrayList<>();
            // 根据产生的数据，通过时间进行分组，将景点名称、平均速度、拥堵情况进行归类组成不同的集合
            for (String s : hourDataList) {
                int carCnt = 0;
                for (Map.Entry<String, List<JSONObject>> entry : currentMonthDataHourDataMap.entrySet()) {
                    if (entry.getKey().equals(s)) {
                        carCnt = Integer.parseInt(entry.getValue().get(0).getString("Person_Cnt"));
                    }
                }
                data1.add(carCnt);
            }

            List<JSONObject> lastMonthData = changeACTMapper.getCustomerAnalysis(townNumber, villageNumber, "lastMonth");
            java.util.Map<String, List<JSONObject>> lastMonthDataHourDataMap = lastMonthData.stream().collect(Collectors.groupingBy(jsonObject -> jsonObject.getString("Hour_Data")));

            List<Integer> data2 = new ArrayList<>();
            // 根据产生的数据，通过时间进行分组，将景点名称、平均速度、拥堵情况进行归类组成不同的集合
            for (String s : hourDataList) {
                int carCnt = 0;
                for (Map.Entry<String, List<JSONObject>> entry : lastMonthDataHourDataMap.entrySet()) {
                    if (entry.getKey().equals(s)) {
                        carCnt = Integer.parseInt(entry.getValue().get(0).getString("Person_Cnt"));
                    }
                }
                data2.add(carCnt);
            }


            List<JSONObject> legendData = new ArrayList<>();
            JSONObject legend1 = new JSONObject();
            legend1.put("name", "当前客流量");
            legend1.put("code", "data1");
            legendData.add(legend1);
            JSONObject legend2 = new JSONObject();
            legend2.put("name", "上月客流量");
            legend2.put("code", "data2");
            legendData.add(legend2);



            JSONObject jsonObject = new JSONObject();

            jsonObject.put("xData", hourDataList);
            jsonObject.put("legend", legendData);
            jsonObject.put("data1", data1);
            jsonObject.put("data2", data2);
            return jsonObject;
        }
        return null;
    }

    @Override
    public JSONObject getCustomerRealTime(String townNumber, String villageNumber,int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<JSONObject> customerRealTime = changeACTMapper.getCustomerRealTime(townNumber, villageNumber);
        PageInfo<JSONObject> pageInfo = new PageInfo<>(customerRealTime);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list", pageInfo.getList());
        jsonObject.put("total", pageInfo.getTotal());
        return jsonObject;
    }

    @Override
    public List<JSONObject> getScenicSpotCoordsList(String townNumber, String villageNumber) {
        List<JSONObject> scenicSpotCoordsList = changeACTMapper.getScenicSpotCoordsList(townNumber, villageNumber);
        for (JSONObject jsonObject : scenicSpotCoordsList) {
            List<JSONObject> scenicSpotCameraList = changeACTMapper.getScenicSpotCameraList(jsonObject.getString("Scenic_Spot_SerialNumber"));
            jsonObject.put("scenicSpotCameraList", scenicSpotCameraList);
        }
        return scenicSpotCoordsList;
    }
}
